using GoodDotNet.IService;
using GoodDotNet.Core.Entity;
using GoodDotNet.Core.Model;
using GoodDotNet.Core.Data;

namespace GoodDotNet.Service
{
    public class AdminRoleModuleService :BaseService,AdminRoleModuleIService
    {
        public AdminRoleModuleService(UnitOfWork _unitOfWork) : base(_unitOfWork)
        {
        }

        public void Add(ParInsertAdminRoleModuleModel pars)
		{
			AdminRoleModule entity=new AdminRoleModule();
			
			entity.RoleId=pars.role_id;
			
			entity.ModuleId=pars.module_id;
			
			entity.Uid=pars.uid;
			
			entity.Btns=pars.btns;
			
			 
		    _unitOfWork.AdminRoleModuleRepository.Add(entity);
		    _unitOfWork.SaveChanges();
		
		}
		
				
		public DataGetOneAdminRoleModuleModel? GetOne(ParGetOneAdminRoleModuleModel pars)
		{
			
			var data = _unitOfWork.AdminRoleModuleRepository.Get(a=>a.Id ==pars.id,t=>new DataGetOneAdminRoleModuleModel{ModuleId=t.ModuleId,Id=t.Id,Btns=t.Btns,Uid=t.Uid});
			
			return data;
		  
		}
        

        public List<RouteModel>? GetListByRole(int roleId)
        {

            var modules = _unitOfWork.AdminModuleRepository.ListByRole(roleId);
        
            return modules;

        }
        public List<AdminRoleModuleGetListByModule>? GetListByModule(int moduleId)
        {
            var mRol = _unitOfWork.AdminRoleModuleRepository.GetList(a=>a.ModuleId==moduleId).ToArray();
            
            var roles = _unitOfWork.AdminRoleRepository.GetList(a=>a.Deleted==0);
            var list = roles.Select(r => new AdminRoleModuleGetListByModule
            {
                Id = r.Id,
                RoleName = r.RoleName,
                Description = r.Description,
                Btns=mRol.Where(a=>a.RoleId==r.Id).FirstOrDefault()?.Btns,
                hasPermission=mRol.Where(a=>a.RoleId == r.Id).FirstOrDefault()!=null,
            }).ToList();

            return list;

        }

        public int Delete(ParDeleteAdminRoleModuleModel pars)
		{
				System.FormattableString sql = $"delete from admin_role_module where  id=#{pars.id}";
				return _unitOfWork.AdminRoleModuleRepository.ExecuteSql(sql);
		}




		public void UpdateRoleModuleBtns(AdminRoleModuleUpdateRoleModuleBtnsParModel pars)
		{
			AdminRoleModule entity = _unitOfWork.AdminRoleModuleRepository.Get(a => a.RoleId == pars.roleId&&a.ModuleId==pars.moduleId);
			if (entity != null) { 
			entity.Btns = pars.btns;
			_unitOfWork.AdminRoleModuleRepository.Update(entity);
			_unitOfWork.SaveChanges();
		}
		
		}
		
		
}
}
